//
//  StateView.swift
//  TSKitDemo
//
//  Created by chenyusen on 2017/9/30.
//  Copyright © 2017年 TechSen. All rights reserved.
//

import UIKit
import SnapKit



open class StateView: UIView {
    
    lazy public var titleLabel: UILabel = {
        let aLabel = UILabel(textColor: DefaultConfig.Color.stateTitle, font: DefaultConfig.Font.stateTitle)
        addSubview(aLabel)
        return aLabel
    }()
    
    
    lazy public var imageView: UIImageView = {
        let aImageView = UIImageView()
        addSubview(aImageView)
        return aImageView
    }()
    
    private var title: String?
    private var image: UIImage?
    private var actionButton: UIButton?
    
    public init(title: String?, image: UIImage?) {
        super.init(frame: CGRect.zero)
        backgroundColor = .clear
    }
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func bind(title: String?, image: UIImage?) {
        if let title = title {
            titleLabel.isHidden = false
            titleLabel.text = title
        } else {
            titleLabel.isHidden = true
            titleLabel.text = nil
        }
        
        if let image = image {
            imageView.image = image
            imageView.isHidden = false
        } else {
            imageView.image = nil
            imageView.isHidden = true
        }
    }
    
    private func setupConstraints() {
        if !imageView.isHidden {
            imageView.snp.remakeConstraints({ (make) in
                make.centerX.equalToSuperview()
                make.bottom.equalTo(snp.centerY).offset(DefaultConfig.Layout.centerYOffset)
            })
        }
        
        if !titleLabel.isHidden {
            titleLabel.snp.remakeConstraints({ (make) in
                make.centerX.equalToSuperview()
                if !imageView.isHidden {
                    make.top.equalTo(imageView.snp.bottom).offset(20)
                } else {
                    make.centerY.equalToSuperview().offset(DefaultConfig.Layout.centerYOffset)
                }
            })
        }
    }
    
    public func add(target: AnyObject?, selector: Selector) {
        if actionButton == nil {
            actionButton = UIButton()
            addSubview(actionButton!)
        }
        actionButton?.snp.makeConstraints({ (make) in
            make.edges.equalToSuperview()
        })
        actionButton?.addTarget(self, action: selector, for: .touchUpInside)
    }
    
}
